import React, { useEffect, useCallback, useState, useReducer, Dispatch, useMemo, memo, forwardRef } from 'react';
import { Title } from '@/components/common'
import { EditStatus } from 'gantd';
import LoupeSelect from '@/components/form/loupeselect';
import { columns } from './schema'
import { findIndex, get } from 'lodash'
import { ActionType, StateType, initState, reducer } from '../codelistselector/reducer'
import { fetchPropsListApi } from './service';
import { uniq } from 'lodash'

export interface ObjectSelectorProps {
    value?: string | string[],
    onChange?: (value: string | string[], valObject?: any) => void,
    bizEntryId?: string,
    defalutValue?: string | string[],
    edit?: EditStatus.EDIT | EditStatus.CANCEL | EditStatus.SAVE,
    initData?: any[],
    allowEdit?: boolean,
    valueProp?: string,
    labelProp?: string
}

function Bizpropselector({ initData = [], ...props }: ObjectSelectorProps, ref: any) {
    const {
        defalutValue,
        allowEdit,
        value: _value,
        onChange,
        bizEntryId,
        edit = EditStatus.EDIT,
        valueProp = "id",
        labelProp = "title",
        ...otherProps
    } = props;

    const [state, dispatch]: [StateType, Dispatch<ActionType>] = useReducer(reducer, initState);

    const {
        value,
        dropDownData,
        modalData,
        loading
    } = state;

    const queryBySelect = useCallback(async () => {
        const data = await fetchPropsListApi({ ...initState.params, bizEntryId });
        dispatch({ type: "saveDropDownData", payload: data });
    }, [bizEntryId])

    useEffect(() => {
        dispatch({ type: "saveValue", payload: _value });
    }, [_value])

    useEffect(() => {
        defalutValue && dispatch({ type: "saveValue", payload: defalutValue });
    }, [])

    useEffect(() => {
        (bizEntryId) && queryBySelect()
    }, [bizEntryId, queryBySelect])

    //当值改变的时候
    const onValueChange = useCallback((value: any, rows: any) => {
        dispatch({ type: "saveValue", payload: value });
        const index = findIndex(dropDownData, { [valueProp]: value })
        if (onChange) onChange(get(dropDownData, `${[index]}`, {}), value)
    }, [onChange, dropDownData, valueProp])

    //查询数据
    const queryByModal = useCallback(async (params) => {
        if (!bizEntryId) return;

        await dispatch({ type: "save", payload: { params, loading: true } });

        const data = await fetchPropsListApi({ ...initState.params, ...params, bizEntryId });

        dispatch({ type: 'save', payload: { modalData: data, loading: false } })
    }, [bizEntryId])

    //是否显示弹框
    const onModalVisibleChange = useCallback(async (visible) => {
        visible ? queryByModal(initState.params) : dispatch({ type: "initModal" })
    }, [bizEntryId])

    return <LoupeSelect
        {...otherProps}
        selectorId={`LoupeSelectBizprops-${bizEntryId}`}
        value={value}
        dataSource={dropDownData}
        edit={edit}
        labelProp={labelProp}
        valueProp={valueProp}
        onChange={onValueChange}
        multiple={false}
        allowEdit={allowEdit}
        itemState={{ width: 640, height: 520 }}
        viewProps={{
            title: <Title title={tr("关联属性")} />,
            onModalVisibleChange,
            viewKey: `LoupeTable-bizprops-${bizEntryId}`,
            columns,
            dataSource: modalData,
            loading: loading,
        }}
    />
}

export default memo(forwardRef(Bizpropselector))